#include "user.h"
#include "cookiejar.h"

#include <QWebView>
#include <QtDebug>

User * User::sInstance = 0;

User::User() : QObject() {}

// Read storage and try to login.
// If logging in is sucessful, User::isLoggedIn() will be true
void User::init() {
    this->mIsLoggedIn = false;

    this->mCookieJar = new CookieJar();
    this->mCookieJar->read();
    this->login( this->mCookieJar->activeAccount(), this->mCookieJar->activeTokenPair() );
}

// Try to login with this token pair. 
// Will save to storage only if logging in is successful.
void User::login( QString username, OAuthTokenPair tok ) {
    if ( username.isEmpty() || tok.token().isEmpty() || tok.secret().isEmpty() ) {
        return;
    }

    this->mUsername = username;
    this->mTokenPair = tok;

    // TODO: check if user logged in successfully [?]
    this->mCookieJar->store();
    this->mIsLoggedIn = true;

    emit this->loggedIn();
}

// Try to login using the browser cookies.
void User::loadFromBrowser( QWebView * browser ) {
    // use cookie jar to fetch cookies
    this->mCookieJar->fromNetworkManager( browser->page()->networkAccessManager() );

    // try to login with active token pair
    this->login( this->mCookieJar->activeAccount(), this->mCookieJar->activeTokenPair() );

    // TODO: if active token pair fails, try other tokens?
}

// Logout and clear storage.
// After this call User::isLoggedIn() will return false.
void User::logout() {
    this->mIsLoggedIn = false;
    this->mUsername = "";
    this->mCookieJar->clearStorage();

    emit this->loggedOut();
}

// return true if user is logged in
bool User::isLoggedIn() {
    return this->mIsLoggedIn;
}

// return the active user instance
User * User::instance() {
    if ( User::sInstance == 0 ) {
        User::sInstance = new User();
    }
    return User::sInstance;
}

QString User::username() {
    return this->mUsername;
}

OAuthTokenPair User::tokenPair() {
    return this->mTokenPair;
}

void User::startLogin() {
    emit this->loginStartRequest();
}
